package com.dxy.dataManage.controller;

import com.dxy.dataManage.bean.Msg;
import com.dxy.dataManage.bean.User;
import com.dxy.dataManage.mapper.UserMapper;
import com.dxy.dataManage.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author dxy
 * @version 1.0
 */
@Controller
public class UserController {

    @Resource
    private UserService userService;
    @Resource
private UserMapper userMapper;
    @RequestMapping(value = "/hello")
    @ResponseBody
    public String hello() {
        System.out.println("hello");
        return "hello";
    }

    @RequestMapping("/login")
    @ResponseBody
    public Msg login(@RequestBody User user, HttpSession session) {
        Msg msg;
        System.out.println("user => " + user);
        //判断不能为空
        if (!StringUtils.hasText(user.getName()) || !StringUtils.hasText(user.getPassword())) {
            return Msg.fail().add("message", "用户名或密码不能为空");
        }
        //从数据库核对
        User dbUser = userService.getByName(user.getName());
        System.out.println("dbUser => " + dbUser);
        if (null == dbUser){
            return Msg.fail().add("message", "用户名不存在");
        }
        if (dbUser.getName().equals(user.getName()) && dbUser.getPassword().equals(user.getPassword())) {
            System.out.println("--放入 session  开始操作--");
            session.setAttribute("loginAdmin", user);
            System.out.println("放入的loginAdmin = " + session.getAttribute("loginAdmin"));
            System.out.println("sessionId => " + session.getId());
            System.out.println(dbUser.getName() + " - 登陆成功");
            return Msg.success().add("message", "登陆成功").add("componyName", dbUser.getCompanyname()).add("componyId", dbUser.getId());
        } else {
            msg = Msg.fail();
            msg.add("message", "密码输入错误");
            return msg;
        }

    }

    @RequestMapping("/exit")
    public Msg exit(HttpSession session) {
        System.out.println("--删除 session  开始操作--");
        System.out.println("删除操作获取到的loginAdmin = " + session.getAttribute("loginAdmin"));
        System.out.println("sessionId => " + session.getId());
        session.removeAttribute("loginAdmin");
        return Msg.success();
    }
}
